/**
 * 
 */
package com.cplsystems.incidencias.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cplsystems.incidencias.app.utils.HibernateDAOSuportUtil;
import com.cplsystems.incidencias.business.DatosGenerales;
import com.cplsystems.incidencias.business.Persona;
import com.cplsystems.incidencias.dao.DatosGeneralesDAO;

/**
 * @author César Palalía López (csr.plz@aisa-automation.com)
 * 
 */
@Repository
public class DatosGeneralesDAOImpl extends HibernateDaoSupport implements
		DatosGeneralesDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory)
			throws DataAccessException {
		setSessionFactory(sessionFactory);
	}

	@Transactional
	public void save(DatosGenerales datosGenerales) {
		getHibernateTemplate().saveOrUpdate(datosGenerales);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<DatosGenerales> findPersonaByNombreApellidosPaterno(
			String nombre, String apellidoPaterno) {
		Criteria criteria = getHibernateTemplate().getSessionFactory()
				.openSession().createCriteria(DatosGenerales.class);
		criteria.setFetchMode("persona", FetchMode.SELECT);
		criteria.add(Restrictions.like("nombre", "%" + nombre + "%"));
		criteria.add(Restrictions.like("apellidoPaterno", "%" + apellidoPaterno
				+ "%"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<DatosGenerales> findPersonaByNombre(String nombre) {
		Criteria criteria = getHibernateTemplate().getSessionFactory()
				.openSession().createCriteria(DatosGenerales.class);
		criteria.setFetchMode("persona", FetchMode.SELECT);
		criteria.add(Restrictions.like("nombre", "%" + nombre + "%"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<DatosGenerales> findByApellidos(String apellidoPaterno) {
		Criteria criteria = getHibernateTemplate().getSessionFactory()
				.openSession().createCriteria(DatosGenerales.class);
		criteria.setFetchMode("persona", FetchMode.SELECT);
		criteria.add(Restrictions.like("apellidoPaterno", "%" + apellidoPaterno
				+ "%"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public DatosGenerales getDatosGeneralesByPersona(Persona persona) {
		List<DatosGenerales> datosGenerales = getHibernateTemplate().find(
				"FROM DatosGenerales as d WHERE d.persona = ?", persona);
		return datosGenerales.size() > 0 ? datosGenerales.get(0) : null;
	}
}
